// 扫描开关存储键
const KEY = (hostname) => `scan_${hostname}`

// 接收消息
chrome.runtime.onMessage.addListener((msg, sender) => {
    switch (msg.cmd) {
        case 'setBadge':
            // 设置图标角标：采集到的图片数量
            chrome.action.setBadgeText({text: msg.text, tabId: sender.tab.id})
            break
        default:
            // 默认处理
            break
    }
})

// 安装时创建右键菜单 （一个扩展如果有多个菜单，会自动合并到二级菜单）
chrome.runtime.onInstalled.addListener(() => {
    chrome.contextMenus.create({
        id: "download-all-images",
        title: "下载页面全部图片",
        contexts: ["page", "image"]
    })
    chrome.contextMenus.create({
        id: "download-all-images-stop",
        title: "关闭页面图片扫描",
        contexts: ["page", "image"]
    })
    chrome.contextMenus.create({
        id: "download-all-images-start",
        title: "开启页面图片扫描",
        contexts: ["page", "image"]
    })
})

/* 读取缓存值并刷新菜单 */
async function refreshMenu(tab) {
    if (!tab || !tab.url || tab.url === "") return
    const hostname = new URL(tab.url).hostname
    let scanning = true
    try {
        const data = await chrome.storage.local.get(KEY(hostname))
        scanning = data[KEY(hostname)] !== false
        chrome.contextMenus.update('download-all-images', {visible: scanning})
        chrome.contextMenus.update('download-all-images-stop', {visible: scanning})
        chrome.contextMenus.update('download-all-images-start', {visible: !scanning})
        chrome.contextMenus.refresh?.()
    } catch (_) {
        scanning = true
        chrome.contextMenus.update('download-all-images', {visible: scanning})
        chrome.contextMenus.update('download-all-images-stop', {visible: scanning})
        chrome.contextMenus.update('download-all-images-start', {visible: !scanning})
        chrome.contextMenus.refresh?.()
    }
    // 发送状态通知
    chrome.tabs.sendMessage(tab.id, {type: 'SET_SCAN', enabled: scanning})
}

// 页面加载完成后恢复状态并刷新菜单
chrome.tabs.onUpdated.addListener(async (tabId, changeInfo, tab) => {
    if (changeInfo.status === 'complete') {
        await refreshMenu(tab)
    }
})

// 用户切换标签页
chrome.tabs.onActivated.addListener(async activeInfo => {
    const tab = await chrome.tabs.get(activeInfo.tabId)
    await refreshMenu(tab)
})

// 点击右键菜单
chrome.contextMenus.onClicked.addListener(async (info, tab) => {
    const hostname = new URL(tab.url).hostname
    switch (info.menuItemId) {
        case "download-all-images":
            // 右键：下载所有图片
            await downloadAllImages(tab)
            break
        case "download-all-images-stop":
            // 右键：关闭图片扫描
            const data_1 = await chrome.storage.local.get(KEY(hostname))
            const newState_1 = !(data_1[KEY(hostname)] !== false) // 取反
            await chrome.storage.local.set({[KEY(hostname)]: newState_1})
            await refreshMenu(tab)
            break
        case "download-all-images-start":
            // 右键：开启图片扫描
            const data = await chrome.storage.local.get(KEY(hostname))
            const newState = !(data[KEY(hostname)] !== false) // 取反
            await chrome.storage.local.set({[KEY(hostname)]: newState})
            await refreshMenu(tab)
            break
        default:
            // 默认处理
            break
    }
})

// 菜单功能：下载所有图片
async function downloadAllImages(tab) {
    // 直接注入调用全局函数
    const [{result: images}] = await chrome.scripting.executeScript({
        target: {tabId: tab.id},
        func: () => window.getCollectedImages?.() || []
    })
    // 遍历图片并下载
    images.forEach((url) => {
        chrome.downloads.download({url: formatUrl(url, tab)})
    })
}

// 格式化图片地址
function formatUrl(url, tab) {
    const webPage = tab.url
    // 先整体拆成两段
    const [base, search] = url.split('?', 2)
    // 1. 没有参数直接返回原串
    if (!search) return url
    // 2. 有参数
    let imgUrl = base
    // 用 URLSearchParams 取到所有的参数
    const params = new URLSearchParams(search)
    // 追加参数：网站图片特有参数。

    // 如果是x.com，则需要截取掉 webPage 的部分
    if (webPage.includes('x.com') || webPage.includes('twitter.com')) {
        // 大图
        imgUrl = imgUrl + '?name=large'
        // 图片格式
        const formatVal = params.get('format')
        if (formatVal) {
            imgUrl = imgUrl + '&format=' + encodeURIComponent(formatVal)
        }
    }

    return imgUrl
}
